import type { MenuNodeType } from '../enums'
import type { IApp } from './app'
import { Tree } from '@pkgs/utils'
import { defineStore } from 'pinia'
import useAppStore from './app'

interface IProject {
  type: MenuNodeType
  name: string
  code: string
  url: string
  active: boolean
  sort: number
  children: IApp[]
}

interface IState {
  projectCode: string
  projects: IProject[]
}

export const useProjectStore = defineStore('project-store', {
  state: (): IState => ({
    projectCode: '',
    projects: [],
  }),

  getters: {
    getProjectCode: state => state.projectCode,

    getProjects: state => state.projects,
  },

  actions: {
    getApps(projectCode: string): IApp[] {
      const apps = this.projects.find(project => project.code === projectCode)?.children ?? []
      new Tree<IApp>().traversal(apps, (app) => {
        app.projectCode = projectCode
      })
      return apps
    },

    setProjectCode(projectCode: string, appCode?: string): IApp[] {
      this.projectCode = projectCode
      const apps = this.getApps(this.projectCode)
      const appStore = useAppStore()
      appStore.setApps(apps, appCode)

      return apps
    },

    setProjects(projects: IProject[]) {
      this.projects = projects
      const activeProject = this.projects.find((project: IProject) => project.active)
      if (activeProject) {
        this.setProjectCode(activeProject.code)
      }

      // const apps = this.getApps(this.getProjectCode)
      // const activeApp = apps.find((app: IApp) => app.active)
      // const appStore = useAppStore()
      // appStore.setApps(apps, activeApp?.code)
    },
  },

  persist: true,
})

export default useProjectStore
